
using System;
using System.Drawing;
using System.Collections.Generic;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.SQLite;
using bjeschool_csharp.Model;

namespace bjeschool
{
	public partial class CommonList : UIViewController
	{
		[Outlet("containerView")]
		public virtual UIView containerView { get; set; }

		public CommonList () : base ("CommonList", null)
		{
		}
	}

	public partial class CommonListEx<T,T2> : CommonList 
		where T : new()
		where T2 : CommonCell<T>, new()
	{
		public event OnRowSelectedDelegate OnRowSelected;

		public override UIView containerView { get; set; }

		private SQLiteConnection conn;
		private CommonTableViewController<T,T2> tablectrl;
		public CommonTableViewController<T,T2> TableViewController {
			get {
				return tablectrl;
			}
		}
		public string[] HeaderTitle { get; set; }

		public CommonListEx (SQLiteConnection db) : base ()
		{
			this.conn = db;
			this.tablectrl = new CommonTableViewController<T,T2>(conn);
		}
		
		public override void DidReceiveMemoryWarning ()
		{
			// Releases the view if it doesn't have a superview.
			base.DidReceiveMemoryWarning ();
			
			// Release any cached data, images, etc that aren't in use.
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// Perform any additional setup after loading the view, typically from a nib.
			this.tablectrl.OnRowSelected += (UITableView tableView, NSIndexPath indexPath) => {
				if(OnRowSelected != null)
					OnRowSelected(tableView, indexPath);
			};
			containerView.AddSubview(this.tablectrl.View);
			containerView.BackgroundColor = new UIColor(246/255f, 246/255f, 246/225f, 1);

			if(RowHeight>0)
				tablectrl.RowHeight = RowHeight;
			tablectrl.TableView.AllowsMultipleSelection = false;
			tablectrl.TableView.BackgroundColor = new UIColor(1,1,1,0);

			//tablectrl.HideSearchBar();
			//tablectrl.TableView.Delegate = new MyUITableViewDelegate();
			tablectrl.HeaderTitle = this.HeaderTitle;
		}

		public float RowHeight {get;set;}
		
		public override void ViewDidUnload ()
		{
			base.ViewDidUnload ();
			
			// Clear any references to subviews of the main view in order to
			// allow the Garbage Collector to collect them sooner.
			//
			// e.g. myOutlet.Dispose (); myOutlet = null;
			
			ReleaseDesignerOutlets ();
		}

		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			// Return true for supported orientations
			return true;
		}
	}

	public class CommonCell<T> : UITableViewCell
	{
		[Outlet("CellView")]
		public virtual UITableViewCell CellView { get; set; }

		public IRowState tableView { get; set; }
		public NSIndexPath indexPath { get; set; }

		public virtual void SetData (T item)
		{
		}
	}

	public delegate void OnRowSelectedDelegate(UITableView tableView, NSIndexPath indexPath);

//	public class MyUITableViewDelegate : UITableViewDelegate{
//		public override UIView GetViewForHeader (UITableView tableView, int section)
//		{
//			Console.Out.WriteLine("GetViewForHeader");
//			return null;
//		}
//
//		public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
//		{
//			return tableView.RowHeight;
//		}
//	}

	public struct RowsState
	{
		public RowsState(bool c, float h)
		{
			collaps = c;
			height = h;
		}
		public bool collaps;
		public float height;
	}

	public interface IRowState
	{
		void SetRowState (NSIndexPath indexPath, RowsState state);
		RowsState GetRowState (NSIndexPath indexPath);
	}

	public class CommonTableViewController<T, T2> : SQLiteTableViewController<T> , IRowState
		where T : new()
		where T2 : CommonCell<T>, new()
	{
		public event OnRowSelectedDelegate OnRowSelected;

		private Dictionary<int, RowsState> rowsheight = new Dictionary<int, RowsState>();
		private string cellNib;
		public CommonTableViewController (SQLiteConnection sqlitedb)
			: base (sqlitedb, 16)
		{
			this.cellNib = typeof(T).ToString();
		}

		public new float RowHeight {
			get {
				return base.RowHeight;
			}
			set {
				base.RowHeight = value;
			}
		}

		private bool isGenHeader = false;
		private string[] headerTitle;
		public string[] HeaderTitle {
			get {
				return headerTitle;
			}
			set {
				headerTitle = value;
			}
		}

		void GenHeader (UITableViewCell cell)
		{
			if (!isGenHeader && headerTitle != null) {
				isGenHeader = true;
				UIView content = cell.Subviews[0];
				UIView view = new UIView(cell.Bounds);
				view.BackgroundColor = UIColor.Gray;

				int count = Math.Min(content.Subviews.Length, headerTitle.Length);
				//Console.Out.WriteLine("Header Count:" + count);
				for(int i=0; i<count; i++)
				{
					//Console.Out.WriteLine("GenHeader");
					UIView subview = content.Subviews[i];
					UILabel fsr = new UILabel(subview.Frame);
					fsr.BackgroundColor = UIColor.Gray;
					fsr.Text = headerTitle[i];
					view.AddSubview(fsr);
				}
				this.TableView.TableHeaderView = view;
			}
		}

		public RowsState GetRowState (NSIndexPath indexPath)
		{
			if(!rowsheight.ContainsKey(indexPath.Row))
				rowsheight[indexPath.Row] = new RowsState();
			return rowsheight[indexPath.Row];
		}

		public void SetRowState (NSIndexPath indexPath, RowsState state)
		{
			rowsheight[indexPath.Row] = state;
			TableView.ReloadRows(new NSIndexPath[]{indexPath}, UITableViewRowAnimation.Automatic);
		}

		protected override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
		{
			if (rowsheight.ContainsKey(indexPath.Row)) 
			{
				//if(rowsheight[indexPath.Row].collaps)
					return rowsheight[indexPath.Row].height;
			}
			return base.GetHeightForRow(tableView, indexPath);
		}

		protected override UIView GetViewForHeader (UITableView tableView, int section)
		{
			Console.Out.WriteLine("GetViewForHeader");
			//GenHeader();
			return base.GetViewForHeader (tableView, section);
		}

		// Note: This is the only method, other than the .ctor, that we actually need to implement in
		// order to have a functional SQLiteTableViewController capable of displaying data from our
		// SQLite table.
		protected override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath, T item)
		{
			//Console.Out.WriteLine("GetCell");
			var cell = tableView.DequeueReusableCell (cellNib);
			if (cell == null)
				cell = new T2 ();
//			else
//				Console.Out.WriteLine ("ReusableCell");
			CommonCell<T> cell2 = cell as CommonCell<T>;
			cell2.tableView = this;
			cell2.indexPath = indexPath;
			cell2.SetData (item);
			GenHeader (cell2.CellView);
			return cell2.CellView;
		}
		
		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			return true;
		}

		protected override void RowSelected (UITableView tableView, NSIndexPath indexPath)
		{
			// Navigation logic may go here -- for example, create and push another view controller.
			OnRowSelected(tableView, indexPath);
		}
	}
}

